package com.training.controller;

import com.training.entity.Student;
import com.training.entity.User;
import com.training.service.PurchaseRecordService;
import com.training.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/purchase")
public class PurchaseController {

    @Autowired
    private PurchaseRecordService purchaseRecordService;

    @Autowired
    private StudentService studentService;

    @PostMapping("/now/{courseId}")
    public String purchaseNow(@PathVariable("courseId") Long courseId,
                              HttpSession session,
                              RedirectAttributes redirectAttributes) {

        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"STUDENT".equalsIgnoreCase(loggedInUser.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "请先以学生身份登录！");
            return "redirect:/login";
        }

        Student student = studentService.getStudentByUserId(loggedInUser.getId());
        if (student == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "未找到您的学生信息，无法购买。");
            return "redirect:/course/browse";
        }

        try {
            boolean success = purchaseRecordService.purchaseCourse(student.getId(), courseId);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "购买成功！课程已添加到“我的课程”。");
                // 购买成功，跳转到“我的课程”页面
                return "redirect:/student/my-courses";
            } else {
                // purchaseCourse 方法内部已经处理了“已购买”和“积分不足”的情况，并返回false
                redirectAttributes.addFlashAttribute("errorMessage", "购买失败！原因可能是积分不足或您已拥有该课程。");
                return "redirect:/course/browse";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "购买过程中发生错误：" + e.getMessage());
            return "redirect:/course/browse";
        }
    }
}